#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage : " << argv[0] << " server-ip  server-port\n"
                  << std::endl;
        exit(0);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 1.创建sockfd
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(0);
    }
    struct sockaddr_in peer;
    memset(&peer, 0, sizeof(peer));
    peer.sin_family = AF_INET;
    inet_pton(AF_INET, ip.c_str(), &peer.sin_addr);
    peer.sin_port = htons(port);

    // 连接服务器
    int n = connect(sockfd, (struct sockaddr *)&peer, sizeof(peer));
    if (n < 0)
    {
        std::cerr << "connect socket error" << std::endl;
        exit(2);
    }
    // 处理业务
    while (true)
    {
        std::string message;
        std::cout << "Enter #";
        std::getline(std::cin, message);
        write(sockfd, message.c_str(), message.size());

        char echo_buff[1024];
        int res = read(sockfd, echo_buff, sizeof(echo_buff) - 1);
        if (res > 0)
        {
            echo_buff[res] = 0;
            std::cout << echo_buff << std::endl;
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}